require "http"

class Api::V1::PagesController < Api::V1::BaseController
  skip_before_action :authenticate_request!
  before_action :authenticate_request

  def categories
    @categories = [{
      :id => 0,
      :name => '品牌墙',
      :type => 'Brand'
    }]
    @shop_categories = ShopCategory.where("parent_id = 0 OR parent_id IS NULL").order("sort ASC")
    @shop_categories.each do |shop_category|
      @categories.push({
        :id => shop_category.id,
        :name => shop_category.name,
        :type => shop_category.class.name
      })
    end
  end

  def brands_wall
    @shop_categories = ShopCategory.where("parent_id = 0 OR parent_id IS NULL").order("sort ASC")
  end
  
  def recommend
    @skus = Sku.joins(:spu).where(:spus => {state: :onsale, published: true, show_index: true}).order('created_at DESC').page(params[:page]).per(params[:per])
    # @spus = Spu.where(state: :onsale, published: true, show_index: true).order('created_at DESC').page(params[:page]).per(params[:per])
  end

  def brands
    @brands = Brand.where(show_index: true).order('sort ASC').limit(10)
  end
  
  def seckills
    # @seckills = SeckillSpu.between_times(Time.zone.now, Time.zone.now + 2.hours)
    @seckills = SeckillSpu.all
  end

  def search
    if params[:search_key].blank?
      @spus = []
    else
      @spus = Spu.where(state: :onsale, published: true).where("name LIKE ?", "%#{params[:search_key]}%").order("created_at DESC")
    end
  end

  def headlines
    clearance_spus = Spu.joins(:skus).where(promotion: true).where("skus.promotion_price <= (skus.sale_price - skus.cost_price) / 2 + skus.cost_price").order("created_at DESC").limit(2)
    clearance_items = []
    clearance_spus.each do |spu|
      clearance_items.push({ id: spu.id, avatar: spu.avatar.url })
    end
    clearances = {
      name: "精品促销",
      type: "app",
      page: "clearance_list_page",
      params: "",
      items: clearance_items
    }
    today_spus = Spu.where(state: :onsale, published: true).order("created_at DESC").limit(2)
    today_items = []
    today_spus.each do |spu|
      today_items.push({ id: spu.id, avatar: spu.avatar.url })
    end
    new_in_today = {
      name: "每日更新",
      type: "app",
      page: "day_goods_page",
      params: "{ \"newest\": true }",
      items: today_items
    }

    shops_in_near = {
      name: "附件门店",
      type: "shop",
      params: "",
      items: []
    }
    if params[:latitude].presence && params[:longitude].presence
      location = "#{params[:latitude]},#{params[:longitude]}"
      shops = Shop.within(5, origin: [params[:latitude], params[:longitude]]).where(state: :opening).order("distance ASC").limit(2)
      shop_items = []
      shops.each do |shop|
        shop_items.push({ id: shop.id, avatar: shop.avatar.url })
      end
      shops_in_near = {
        name: "附近门店",
        type: "app",
        page: "near_store_list_page",
        params: "",
        items: shop_items
      }
    end
    
    handpick_spus = Spu.where(handpick: true, state: :onsale, published: true).order("created_at DESC").limit(2)
    handpick_items = []
    handpick_spus.each do |spu|
      handpick_items.push({ id: spu.id, avatar: spu.avatar.url })
    end
    handpicks = {
      name: "产品严选",
      type: "app",
      page: "yan_xuan_page",
      params: "",
      items: handpick_items
    }

    @headlines = [shops_in_near, new_in_today, clearances, handpicks]
  end

  def clearance
    @spus = Spu.where(promotion: true)
    if params[:shop_category_id].presence
      @spus = @spus.where(shop_category_id: params[:shop_category_id])
    end
    @spus = @spus.page(params[:page]).per(params[:per])
  end

  def notices
    @notices = []
    if ActiveModel::Type::Boolean.new.cast(Setting.fetch("use_notice_board"))
      Order.where("state = 1 || state = 2 || state = 3").order("created_at DESC").limit(10).each do |order|
        if order.user.presence && order.order_items.count > 0
          @notices.push({
            name: "#{order.user.nickname}购买了#{order.order_items.first.spu_name}",
            type: '',
            page: ''
          })
        end
      end
    end
  end

  def update_region
    Province.all.each do |province|
      if province.adcode.blank? || province.longitude.blank? || province.latitude.blank?
        url = "https://restapi.amap.com/v3/geocode/geo?address=#{province.name}&key=#{Figaro.env.amap_key}"
        response = JSON.parse(HTTP.get(url))
        province.update(
          adcode: response["geocodes"][0]["adcode"],
          longitude: response["geocodes"][0]["location"].split(',')[0],
          latitude: response["geocodes"][0]["location"].split(',')[1]
        )
      end

      province.cities.each do |city|

        if city.adcode.blank? || city.longitude.blank? || city.latitude.blank?
          url = "https://restapi.amap.com/v3/geocode/geo?address=#{province.name}#{city.name}&key=#{Figaro.env.amap_key}"
          response = JSON.parse(HTTP.get(url))
          city.update(
            adcode: response["geocodes"][0]["adcode"],
            longitude: response["geocodes"][0]["location"].split(',')[0],
            latitude: response["geocodes"][0]["location"].split(',')[1]
          )
        end

        city.districts.each do |district|
          if district.adcode.blank? || district.longitude.blank? || district.latitude.blank?
            url = "https://restapi.amap.com/v3/geocode/geo?address=#{province.name}#{city.name}#{district.name}&key=#{Figaro.env.amap_key}"
            response = JSON.parse(HTTP.get(url))
            district.update(
              adcode: response["geocodes"][0]["adcode"],
              longitude: response["geocodes"][0]["location"].split(',')[0],
              latitude: response["geocodes"][0]["location"].split(',')[1]
            )
          end
        end
      end
    end
    render :json => { data: { success: 1 } }
  end
  
end
